from model.job_classes import JobClasses
from sqlalchemy import distinct, desc, asc


class JobClassesDao(object):
    def __init__(self, session):
        self.session = session

    def get_classes(self):
        datas = []
        q = self.session.query(distinct(JobClasses.class_code).label("class_code"), JobClasses.class_name)
        q.order_by(desc(JobClasses.class_code))
        if q:
            children_dict = self.get_all_posts()
            result = q.all()
            for d in result:
                datas.append(
                    {"code": d.class_code,
                     "name": d.class_name,
                     "children": children_dict.get(d.class_code)})
            return datas
        else:
            return None

    def get_posts_by_class_code(self, class_code):
        data_s = []
        q = self.session.query(JobClasses.class_code,
                               JobClasses.post_code,
                               JobClasses.class_name) \
            .filter(JobClasses.class_code == class_code)
        q.order_by(desc(JobClasses.post_code))
        if q:
            result = q.all()
            for d in result:
                data_s.append(
                    {"class_code": d.class_code,
                     "class_name": d.class_name
                     })
            return data_s
        else:
            return None

    def get_all_posts(self):
        # class_code : [{}]
        f_dict = {}
        q = self.session.query(JobClasses.class_code,
                               JobClasses.post_code,
                               JobClasses.post_name) \
            .order_by(desc(JobClasses.class_code),
                      asc(JobClasses.post_code))
        if q:
            result = q.all()
            for d in result:
                s_list = []
                if not f_dict.get(str(d.class_code)):
                    # s_list.append({"class_code": d.class_code, "code": d.post_code, "name": d.post_name})
                    s_list.append({"code": d.post_code, "name": d.post_name})
                    f_dict[d.class_code] = s_list
                else:
                    s_list = f_dict.get(d.class_code)
                    # s_list.append({"class_code": d.class_code, "code": d.post_code, "name": d.post_name})
                    s_list.append({"code": d.post_code, "name": d.post_name})

            return f_dict
        else:
            return None


if __name__ == '__main__':
    # session = Session()
    # dao = JobClassesDao(session)
    # print(dao.get_classes())
    pass
